﻿using Microsoft.AspNetCore.Mvc;
using RedisLock_Demo.Models;
using System;

namespace RedisLock_Demo.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class RedisLockController : ControllerBase
    {
        readonly IFreeSql freeSql;
        readonly RedisLock redisLock = new RedisLock();
        public RedisLockController(IFreeSql _freeSql)
        {
            freeSql = _freeSql;
        }

        [HttpPost]
        public int Post()
        {
            //请求id
            string requestId = Guid.NewGuid().ToString();
            try
            {
                //获取锁
                redisLock.GetLock(requestId);
                //业务操作
                var redisLockd = freeSql.Select<RedisLockdTest>().First();
                redisLockd.Num++;
                freeSql.Update<RedisLockdTest>().Set(r => r.Num, redisLockd.Num).Where(r => 1 == 1).ExecuteAffrows();
                return redisLockd.Num;
            }
            finally
            {
                redisLock.ReleaseLock(requestId);
            }
        }
    }
}
